package com.googlesource.gerrit.plugins.examples.servlet;

import com.alibaba.fastjson.JSON;
import com.google.gerrit.extensions.annotations.PluginCanonicalWebUrl;
import com.google.gerrit.extensions.annotations.PluginName;
import com.google.gerrit.server.CurrentUser;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;

import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Cookie;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Singleton
public class ValidLoginServlet extends HttpServlet {

    private static final Logger log = LoggerFactory.getLogger(ValidLoginServlet.class);
    private final Provider<CurrentUser> userProvider;
    private static List<String> userList = new ArrayList<>();

    {
        String propertiesWay = System.getProperty("user.dir") + File.separator + "conf" + File.separator
                + "conf.properties";
        PropContainer pro = PropContainer.getInstance(propertiesWay);
        String userListProperty = pro.getProperty("user-list");
        String[] split = userListProperty.split(",");
        userList = Arrays.asList(split);
        log.info("userList读取完毕:{}", userList);
    }

    @Inject
    ValidLoginServlet(@PluginName String pluginName, @PluginCanonicalWebUrl String url,
            Provider<CurrentUser> userProvider) {
        this.userProvider = userProvider;
        log.info(String.format("Cookbook Plugin '%s' at url %s", pluginName, url));
    }

    @Override
    protected void doGet(final HttpServletRequest request, final HttpServletResponse response)
            throws IOException, ServletException {
        if (userProvider.get().isIdentifiedUser() && userList.contains(userProvider.get().getLoggableName())) {
            response.getWriter().println(JSON.toJSONString(new Result(200, "SUCCESS")));
        } else
            response.getWriter().println(JSON.toJSONString(new Result(401, "UNAUTHORIZED")));
    }

    @Override
    protected void doPost(final HttpServletRequest req, final HttpServletResponse rsp)
            throws IOException, ServletException {
        doGet(req, rsp);
    }

}
